var username = getCookie("username");
var li = document.querySelector(".header-con li:first-child");
// console.log(li);
if (username) {
    li.innerHTML = "";
    var str = `
            欢迎${username}光临
            <a href="javascript:;" class="del">退出</a>
    `;
    li.innerHTML = str;
    var del = document.querySelector(".del");
    del.onclick = function () {
        removeCookie("username");
        li.innerHTML = "";
        var str = `
            <a href="login.html" id="login">登陆</a>
            <a href="register.html" id="register">注册</a>
        `;
        li.innerHTML = str;
    }
}
// 如果用户没有登陆，就不要去查询数据
if (!username) {
    $(".shop").empty();
    var div = $("<div style='margin:180px 285px'><img style='vertical-align:middle;padding-top:40px' src='./img/nocar.png' alt=''><span style='font-weight:700;color:#333;margin-left:19px'>购物车内暂时没有商品，登录后将显示您之前加入的商品</span><a href='login.html' style='font-size:14px;color:red;display:block;margin-left:90px;margin-top:-23px'>登陆 </a><a href='list.html' style='font-size:14px;color:#ccc;display:inline-block;margin-left:90px;margin-top:-23px'>去购物> </a><div>");
    $(".shop").append(div);
} else {
    var data = localStorage.getItem("goods");
    if (data) {
        data = JSON.parse(data);
        var info = data.filter(ele => ele.username == username);
        info = JSON.stringify(info);
        if (info == "[]" || !info) {
            // 说明购物车什么东西都没有
            $(".shop").empty();
            var div = $("<div style='margin:180px 285px'><img style='vertical-align:middle;padding-top:40px' src='./img/nocar.png' alt=''><span style='font-weight:700;color:#333;margin-left:19px'>购物车空空如也的哦~，去看看心仪的商品吧~</span><a href='list.html' style='font-size:14px;color:red;display:block;margin-left:90px;margin-top:-23px'>去购物> </a><div>");
            $(".shop").append(div);
        } else {
            var data = localStorage.getItem("goods");
            var arr = JSON.parse(data);
            // 需要获取到相应的用户的购物车的所有商品
            var info = arr.filter(ele => ele.username == username);
            // console.log(info);
            // 获取到用户的所选取的商品信息
            var ids = info.map(ele => ele.goodsid).join(",");
            // console.log(ids);
            // 发送ajax请求获取用户选择的商品信息
            $.ajax({
                url: "./serve/shopCart.php",
                dataType: "json",
                type: "post",
                data: {
                    ids
                },
                success: function (res) {
                    // console.log(res);
                    var str = "";
                    for (var i = 0; i < res.length; i++) {
                        str += `
                        <li>
                            <div class="all fl">
                                <input type="checkbox" class="singleCheck fl"/>
                                <div class="goodsImg fr">
                                    <img src="${res[i].imgpath}" alt="">
                                </div>
                            </div>
                            <div class="info fl">
                                <div class="goodsIntro">
                                    <a href="javascript:;"><p>${res[i].name}</p></a>
                                </div>
                                <div class="pay">
                                    <a href="javascript:;"><i><img src="./img/small3.png" alt=""></i></a>
                                    <a href="javascript:;"><i><img src="./img/small2.png" alt=""></i></a>
                                    <a href="javascript:;"><i><img src="./img/small3.png" alt=""></i></a>
                                </div>
                            </div>
                            <div class="color fl">
                                <p class="colorSort">
                                    <a href="javascript:;">
                                        颜色分类:浅灰色
                                    </a>
                                </p>
                            </div>
                            <div class="price fl">
                                <s><b class="oldPrice">￥99.99</b></s>
                                <b class="nowPrice">￥${res[i].price}</b>
                            </div>
                            <div class="count fl">
                                <div class="choseCount" data-index = "${res[i].id}">
                                    <a href="javascript:;" class="fl decrease">-</a>
                                    <input type="text" data-count = "${res[i].stock}" class="buyCount fl" value="${info.find(ele => ele.goodsid == res[i].id).number}" />
                                    <a href="javascript:;" class="fl increase">+</a>
                                </div>
                            </div>
                            <div class="sallPrice fl">
                                <b>￥19.90</b>
                            </div>
                            <div class="action fl">
                                <p><a href="javascript:;">移入收藏夹</a></p>
                                <p><a href="javascript:;" class="owndel">删除</a></p>
                                <p><a href="javascript:;">相似宝贝</a></p>
                            </div>
                    </li>
                    `
                    }
                    $(".goodsList ul").html(str)
                    // 全选全不选
                    checkAll();
                    // 数量的加减
                    addCut();
                    // 商品单价小计
                    subtotal();
                    // 计算商品的总数和总价格
                    getAll();
                    // 单个删除
                    deleteOne();
                    // 清空购物车
                    clearCar();
                    // 删除选中商品
                    delCheck();
                }
            })

            // 全选全不全
            function checkAll() {
                $(".allCheck").on("click", function () {
                    $(".singleCheck,.allCheck").prop("checked", $(this).prop("checked"))
                    getAll()
                })

                $(".singleCheck").on("click", function () {
                    if ($(".singleCheck:checked").length === $(".singleCheck").length) {
                        $(".allCheck").prop("checked", true);
                    } else {
                        $(".allCheck").prop("checked", false);
                    }
                    if ($(this).prop("checked")) {
                        $(this).parent().parent().css("backgroundColor", "#fff4e8");
                    } else {
                        $(this).parent().parent().css("backgroundColor", "");
                    }
                    getAll();
                })
            }

            // 数量加减
            function addCut() {
                $(".decrease").on("click", function () {
                    var number = $(this).siblings("input").val() - 0;
                    number--;
                    if (number <= 1) {
                        number = 1;
                    }
                    $(this).siblings("input").val(number);
                    // 去本地存储中去查询数据
                    var arr = JSON.parse(localStorage.getItem("goods"));
                    arr.find(ele => ele.goodsid == $(this).parent().attr("data-index") && ele.username == username).number = number;
                    localStorage.setItem("goods", JSON.stringify(arr));
                    // 每次数量改变时就要重新进行一次商品价格的小计
                    subtotal();
                    getAll();
                })

                $(".increase").on("click", function () {
                    var number = $(this).siblings("input").val() - 0;
                    number++;
                    if (number >= $(this).siblings("input").attr("data-count") - 0) {
                        number = $(this).siblings("input").attr("data-count") - 0;
                    }
                    $(this).siblings("input").val(number);
                    // 去本地存储中去查询数据
                    var arr = JSON.parse(localStorage.getItem("goods"));
                    arr.find(ele => ele.goodsid == $(this).parent().attr("data-index") && ele.username == username).number = number;
                    localStorage.setItem("goods", JSON.stringify(arr));
                    // 每次数量改变时就要重新进行一次商品价格的小计
                    subtotal();
                    getAll();
                })

                $(".buyCount").on("change", function () {
                    var number = $(this).val() - 0;
                    if (number >= $(this).attr("data-count") - 0) {
                        number = $(this).attr("data-count") - 0
                    }
                    $(this).val(number);
                    var arr = JSON.parse(localStorage.getItem("goods"));
                    arr.find(ele => ele.goodsid == $(this).parent().attr("data-index") && ele.username == username).number = number;
                    localStorage.setItem("goods", JSON.stringify(arr));
                    // 每次数量改变时就要重新进行一次商品价格的小计
                    subtotal();
                    getAll();
                })

            }

            // 商品单价小计
            function subtotal() {
                // 先获取到商品的商家
                $.each($(".nowPrice"), function (index, ele) {
                    // 获取数量
                    var number = $(ele).parent().siblings(".count").find(".buyCount").val() - 0;
                    //    console.log(number);
                    $(ele).parent().siblings(".sallPrice").children().text("￥" + (number * parseFloat($(ele).text().substring(1))).toFixed(2));
                })
            }

            // 计算总件数和总价格
            function getAll() {
                // 计算总计的时候，应该是商品选中后才可以进行计算，没有选中的不需要进行计算
                var totalNum = 0;
                var totalPrice = 0;
                $(".singleCheck:checked").each(function (index, ele) {
                    totalNum += $(ele).parent().siblings(".count").find(".buyCount").val() - 0;
                    totalPrice += $(ele).parent().siblings(".sallPrice").children().text().substring(1) - 0;
                })
                $(".totalCount").text(totalNum);
                $(".totalMoney").text("￥" + totalPrice)
            }

            // 单个删除
            function deleteOne() {
                $(".owndel").on("click", function () {
                    if (!confirm("您确定要删除吗?")) {
                        return false;
                    }
                    $(this).parent().parent().parent("li").remove();
                    var arr = JSON.parse(localStorage.getItem("goods"));
                    // 寻找删除的选项的下标从本地存储的数组中去删除该条数据
                    var goodsid = $(this).parent().parent().siblings(".count").children(".choseCount").attr("data-index");
                    var index = arr.findIndex(ele => ele.goodsid == goodsid && ele.username == username);
                    arr.splice(index, 1);
                    localStorage.setItem("goods", JSON.stringify(arr));
                    getAll();
                    // 如果全部删除完，需要换页面
                    var data = localStorage.getItem("goods");
                    data = JSON.parse(data);
                    var info = data.filter(ele => ele.username == username);
                    info = JSON.stringify(info);
                    if (info == "[]" || !info) {
                        $(".shop").empty();
                        var div = $("<div style='margin:180px 285px'><img style='vertical-align:middle;padding-top:40px' src='./img/nocar.png' alt=''><span style='font-weight:700;color:#333;margin-left:19px'>购物车空空如也的哦~，去看看心仪的商品吧~</span><a href='list.html' style='font-size:14px;color:red;display:block;margin-left:90px;margin-top:-23px'>去购物> </a><div>");
                        $(".shop").append(div);
                    }
                })
            }

            // 清空购物车
            function clearCar() {
                $(".del").on("click", function () {
                    var data = JSON.parse(localStorage.getItem("goods"));
                    var info = data.filter(ele => ele.username == username);
                    for (var i = 0; i < info.length; i++) {
                        var index = data.indexOf(info[i]);
                        data.splice(index, 1);
                    }
                    localStorage.setItem("goods", JSON.stringify(data));
                    $(".shop").empty();
                    var div = $("<div style='margin:180px 285px'><img style='vertical-align:middle;padding-top:40px' src='./img/nocar.png' alt=''><span style='font-weight:700;color:#333;margin-left:19px'>购物车空空如也的哦~，去看看心仪的商品吧~</span><a href='list.html' style='font-size:14px;color:red;display:block;margin-left:90px;margin-top:-23px'>去购物> </a><div>");
                    $(".shop").append(div);
                })
            }

            // 删除选中商品
            function delCheck() {
                $(".remove-batch").on("click", function () {
                    // $(".singleCheck:checked").parent().parent().remove();
                    var data = JSON.parse(localStorage.getItem("goods"));
                    $(".singleCheck:checked").each(function (index, elem) {
                        // 找到当前用户和对应的商品进行选中删除
                        var info = data.filter(ele => ele.goodsid == $(elem).parent().siblings(".count").children(".choseCount").attr("data-index") && ele.username == username);
                        for (var i = 0; i < info.length; i++) {
                            var index = data.indexOf(info[i]);
                            data.splice(index, 1);
                        }
                        $(this).parent().parent().remove();
                    })

                    localStorage.setItem("goods", JSON.stringify(data));
                    // 重新获取该用户购物车剩余的商品
                    info = data.filter(ele => ele.username == username);
                    var laterInfo = JSON.stringify(info);
                    if (laterInfo == "[]" || !laterInfo) {
                        $(".shop").empty();
                        var div = $("<div style='margin:180px 285px'><img style='vertical-align:middle;padding-top:40px' src='./img/nocar.png' alt=''><span style='font-weight:700;color:#333;margin-left:19px'>购物车空空如也的哦~，去看看心仪的商品吧~</span><a href='list.html' style='font-size:14px;color:red;display:block;margin-left:90px;margin-top:-23px'>去购物> </a><div>");
                        $(".shop").append(div);
                    }
                    // 计算总价和总数量
                    getAll();
                })
            }
        }
    }else {
        $(".shop").empty();
        var div = $("<div style='margin:180px 285px'><img style='vertical-align:middle;padding-top:40px' src='./img/nocar.png' alt=''><span style='font-weight:700;color:#333;margin-left:19px'>购物车空空如也的哦~，去看看心仪的商品吧~</span><a href='list.html' style='font-size:14px;color:red;display:block;margin-left:90px;margin-top:-23px'>去购物> </a><div>");
        $(".shop").append(div);
    }

}

